package tss.client;

import java.io.IOException;

import tss.common.ExtensionStates;
import tss.common.LineStates;

public class Client implements ClientInterface {
	
	private ClientConnection connection;

	public Client() {
		try {
			connection = new ClientConnection(this);
			connection.start();
		} catch(Exception ex) {
			System.out.println(ex.getStackTrace());
		}
	}

	@Override
	public int connectServer(String server, int port) {
		try {
			connection.connectToServer(server, port);
			synchronized(this) { wait(); }
		} catch (InterruptedException ex) {
			System.out.println("Thread interrupted.");
		} catch (IOException ex) {
			System.out.println("Error connecting to server. (IO)");
			System.out.println(ex.getMessage());
			System.out.println(ex.getStackTrace());
		} catch (Exception ex) {
			System.out.println("Error connecting to server.");
			System.out.println(ex.getMessage());
			System.out.println(ex.getStackTrace());
		}
		return connection.getExtensionNumber(); 
	}

	@Override
	public void disconnectServer(int extension) {
		connection.disconnect();
	}

	@Override
	public ExtensionStates[] getExtensionStates() {
		try {
			connection.requestExtensionStates();
			synchronized(this) { wait(); }
		} catch (InterruptedException ex) {
			System.out.println("Thread interrupted.");
			System.out.println(ex.getMessage());
			System.out.println(ex.getStackTrace());
		}
		return connection.getExtensionStates();
	}

	@Override
	public boolean dialConnection(int extension) {
		try {
			connection.callExtension(extension);
			synchronized(this) { wait(); }
		} catch (InterruptedException ex) {
			System.out.println("Thread interrupted.");
			System.out.println(ex.getMessage());
			System.out.println(ex.getStackTrace());
		}
		return connection.getLineState() != LineStates.Open;
	}

	@Override
	public LineStates getLineState() {
		// TODO Auto-generated method stub
		return connection.getLineState();
	}

	@Override
	public boolean terminateConnection() {
		try {
			connection.terminateConnection();
			synchronized(this) { wait(); }
		} catch (InterruptedException ex) {
			System.out.println("Thread interrupted.");
			System.out.println(ex.getMessage());
			System.out.println(ex.getStackTrace());
		}
		return connection.getLineState() == LineStates.Open;
	}

	@Override
	public boolean acceptConnection() {
		try {
			connection.acceptConnection();
			synchronized(this) { wait(); }
		} catch (InterruptedException ex) {
			System.out.println("Thread interrupted.");
			System.out.println(ex.getMessage());
			System.out.println(ex.getStackTrace());
		}
		return connection.getLineState() == LineStates.Talking;	
	}
	
}
